/* eslint-disable array-callback-return,no-undef,no-loop-func */
import uuid from 'node-uuid';
import React, { Component } from 'react';
import { Layout, Form, Modal, Spin, message, Avatar } from 'antd';
import styles from '../../../index.less';
import * as config from '../../../utils/config';
import TabMainTable from './TabMainTable';
import TabProductTable from './Product';
import TabJigSawTable from './Jigsaw';
import TabMaterialTable from './Material';
import TabPrintTable from './Print';
import WorkOrderPpop from './WorkOrderPpop';
import MaterialPpop from './MaterialPpop';
import PrintPpop from './PrintPpop';
import TabBindTable from './Bind';
import baseHigher from '../../Common/baseHigher';
import PpopupPan from '../../../routes/ppopupPan/ppopupPan';
import * as commonFunc from '../../Common/commonFunc';
import Toolbar from '../../Common/ToolBar/ToolBar';
import CheckModel from '../../Common/CheckModel';
import imgCheck from '../../../assets/haveChecked.png';
import imgInvalid from '../../../assets/haveCancel.png';


const { Header, Content } = Layout;
const { confirm } = Modal;

class WorkOrder extends Component {
  constructor(props) {
    super(props);
    this.state = {
      btnData: config.btnData, /* 工具栏按钮 */
      masterConfig: { sId: '' }, // 主表 + 从表 配置
      sId: '', /* 业务数据ID */
      sActiveId: '', /* 窗体Id */
      disabled: false, /* 是否是查看状态 */
      loading: false,
      modalVisible: false, /* 弹窗显示状态 */
      workOrderModalVisible: false, /* 弹窗显示状态 */
      modalPanel: {}, /* 弹窗面板属性 */
      workOrderModalPanel: {}, /* 生产详情 */
      mainTable: '', /* 主表 */
      workOrderData: {},
      workOrderMaterialData: [], /* 材料 */
      workOrderPrintData: [], /* 印刷 */
      workOrderJigSawData: [], /* 拼版 */
      workSlaveData: [], /* 从表 */
      gyCards: [] /* 已选择工艺卡 */,
      hiddenProcess: [], /* 隐藏的非印刷工艺 */
      subjectDataTotal: {}, /* 列表数据汇总 */
      listRecordKey: {
        workOrderMaterialDataKey: '', workOrderPrintDataKey: '', workSlaveDataKey: '', workOrderJigSawDataKey: '',
      }, /* 列表弹窗当前操作行,内部属性根据模块不同自定义 */
      recordRow: '', /* 付款条件具体回带值 */
      gdsformconst: [],
      sTabId: '', /* Tab页ID用于复制到等功能新弹出窗口避免弹出多个窗口 */
      newIdlength: 0, /* 复制到所用到的从表ID数 */
      newIdFlag: true, /* 页面复制数据后刷新渲染 */
      workOrderJigsawSelectKey: '', /* 详情面板选中主键 */
      selectStatus: false,
      visible: false, /* 审核不通过的弹窗 */
      sReturnMessage: [],
      sCheckModelId: '',
      sListFormmasterId: '',
      sFormmasterId: '',
      configureMap: '',
      sFilterOrderBy: '',
      bFilter: '',
      currentData: [],
      pages: {},
      pageSize: '',
      iCountSum: '',
      formData: [],
      currentIndex: '',
      currentIndexFlag: false,
      report: [], /* 打印报表 */
      sBackProcessClassifyData: '', // 工序分类
    };
  }
  componentWillMount() {
    this.setState({
      selectStatus: true,
    });
  }
  componentWillReceiveProps(nextProps) {
    const { dataList } = nextProps.content;
    const { gdsformconst, report } = nextProps;
    if (this.state.gdsformconst.length === 0) {
      this.setState({
        gdsformconst,
      });
    }
    if (this.state.report.length === 0) {
      const btnDataChild = [];
      report.forEach((child, i) => {
        btnDataChild.push({
          sName: `BtnPrint.${i}`,
          showName: child.sReportName,
          bVisible: true,
          sActiveId: '',
          sId: child.sId,
        });
      });
      this.setState({ btnDataChild, report });
    }
    /* 配置 */
    const {
      sDataListTabId, urlData, formRoute, loading, sId, paneType, checkedId, disabled, sParentId, newIds, sFilterOrderBy, bFilter, pageSize, pages, sListFormmasterId, currentData, newkey,
    } = dataList;
    if (urlData !== undefined && Object.keys(urlData).length > 0 && paneType !== undefined && paneType !== '' && nextProps.sTabId === sParentId) {
      const paneKey = new Date().getTime().toString();
      const pane = {
        copyToData: dataList.copyToData, /* 复制到数据 */
        title: urlData.sMenuName,
        route: urlData.sName,
        formId: urlData.sId,
        checkedId,
        disabled,
        key: paneKey,
        sFilterOrderBy,
        bFilter,
        pageSize,
        pages,
        sListFormmasterId,
        currentData,
        newkey,
      };
      this.props.onAddPane(pane);
      return;
    }
    /* 数据Id */
    const { formId } = nextProps;
    /* 弹出窗数据返回,渲染数据并关闭弹出框 */
    if ((nextProps.app.ppopupPane !== undefined &&
        nextProps.app.ppopupPane.mainConfig !== undefined) ? (nextProps.sTabId === nextProps.app.ppopupPane.mainConfig.key
        && nextProps.formRoute === nextProps.app.ppopupPane.mainConfig.route) : false) {
      const { resultValue } = nextProps.app.ppopupPane;
      const { modalType } = nextProps.app.ppopupPane;
      /* 通用弹窗数据返值处理 */
      if ((resultValue !== undefined) && modalType === 'ppopup') {
        /* 数据集名 */
        const { dataName } = nextProps.app.ppopupPane;
        if (dataName.indexOf('_Ppop') > -1) {
          const dataNameSplit = dataName.split('_');
          /* 数据集类型，对象型为Map 数组型为List */
          /* 暂时只出现LIST情况,所以优先处理，以后如遇到MAP情况处理再根据具体业务逻辑改造 */
          const data = this.state[`${dataNameSplit[0]}`];
          const { dataType } = nextProps.app.ppopupPane;
          if (dataType === 'Map') {
            /* 固定为控制表 */
            data.map((item) => {
              if (item.sId === this.state.workOrderJigsawSelectKey) {
                for (const key of Object.keys(resultValue)) {
                  /* 赋值回带配置为#字段#,需取主表相应字段值 */
                  if (typeof (resultValue[`${key}`]) === 'string' && resultValue[`${key}`].startsWith('#') && resultValue[`${key}`].endsWith('#')) {
                    item[`${key}`] = this.state.workOrderData[`${key}`];
                  } else {
                    item[`${key}`] = resultValue[`${key}`];
                  }
                }
              }
              return item;
            });
            this.setState({
              [`${dataName}`]: data,
              modalVisible: false,
              listRecordKey: {
                workOrderMaterialDataKey: '', workOrderPrintDataKey: '', workSlaveDataKey: '', workOrderJigSawDataKey: '',
              },
            });
          } else if (dataType === 'List') {
            /* 数据集回带数据处理 */
            data.map((item) => {
              if (((item.sControlId === this.state.workOrderJigsawSelectKey) && (item.sId === undefined ? item.key : item.sId) === this.state.listRecordKey[`${dataNameSplit[0]}Key`])) {
                for (const key of Object.keys(resultValue)) {
                  /* 赋值回带配置为#字段#,需取主表相应字段值 */
                  if (typeof (resultValue[`${key}`]) === 'string' && resultValue[`${key}`].startsWith('#') && resultValue[`${key}`].endsWith('#')) {
                    item[`${key}`] = this.state.workOrderData[`${key}`];
                  } else {
                    item[`${key}`] = resultValue[`${key}`];
                  }
                }
              }
              return item;
            });
            const { hiddenProcess } = this.state;
            /* 隐藏数据集回带处理 */
            hiddenProcess.map((item) => {
              if (((item.sControlId === this.state.workOrderJigsawSelectKey) && (item.sId === undefined ? item.key : item.sId) === this.state.listRecordKey[`${dataNameSplit[0]}Key`])) {
                for (const key of Object.keys(resultValue)) {
                  /* 赋值回带配置为#字段#,需取主表相应字段值 */
                  if (typeof (resultValue[`${key}`]) === 'string' && resultValue[`${key}`].startsWith('#') && resultValue[`${key}`].endsWith('#')) {
                    item[`${key}`] = this.state.workOrderData[`${key}`];
                  } else {
                    item[`${key}`] = resultValue[`${key}`];
                  }
                }
              }
              return item;
            });
            let hiddenProcessNew = [];
            let dataAll = data;
            let printFlag = 0;
            if (dataNameSplit[0] === 'workOrderPrintData') {
              printFlag = 1;
              dataAll = [...data, ...hiddenProcess];
              /* 循环非隐藏数据 */
              let count = 0;
              while (count < dataAll.length) {
                if (dataAll[count].sType !== '1') {
                  hiddenProcessNew.push(dataAll[count]);
                  dataAll.splice(count, 1);
                  count -= 1;
                }
                count += 1;
              }
            }
            /* 物料回带时隐藏数据还是为原来的,不进行处理 */
            if (printFlag === 0) {
              hiddenProcessNew = hiddenProcess;
            }
            /* 弹窗数据回填后，清空listRecordKey 避免数据污染 */
            this.setState({
              [`${dataNameSplit[0]}`]: dataAll,
              hiddenProcess: hiddenProcessNew,
              modalVisible: false,
              listRecordKey: {
                workOrderMaterialDataKey: '', workOrderPrintDataKey: '', workSlaveDataKey: '', workOrderJigSawDataKey: '',
              },
            });
          }
        } else {
          /* 数据集类型，对象型为Map 数组型为List */
          const { dataType } = nextProps.app.ppopupPane;
          const data = this.state[`${dataName}`];
          if (dataType === 'Map') {
            for (const key of Object.keys(resultValue)) {
              data[`${key}`] = resultValue[`${key}`];
            }
            this.setState({ [`${dataName}`]: data, modalVisible: false });
          } else if (dataType === 'List') {
            data.map((item) => {
              if ((item.sId === undefined ? item.key : item.sId) === this.state.listRecordKey[`${dataName}Key`]) {
                for (const key of Object.keys(resultValue)) {
                  /* 赋值回带配置为#字段#,需取主表相应字段值 */
                  if (typeof (resultValue[`${key}`]) === 'string' && resultValue[`${key}`].startsWith('#') && resultValue[`${key}`].endsWith('#')) {
                    item[`${key}`] = this.state.workOrderData[`${key}`];
                  } else {
                    item[`${key}`] = resultValue[`${key}`];
                  }
                }
              }
              return item;
            });
            /* 弹窗数据回填后，清空listRecordKey 避免数据污染 */
            this.setState({
              [`${dataName}`]: data,
              modalVisible: false,
              listRecordKey: {
                workOrderMaterialDataKey: '', workOrderPrintDataKey: '', workSlaveDataKey: '', workOrderJigSawDataKey: '',
              },
            });
          }
        }
        /* 弹出框关闭 */
        this.props.onRemoveModalPane({});
        return;
      }
    }
    /* 窗体全部配置 */
    const masterConfig = commonFunc.getWindowConfig('mftworkordermaster', nextProps.formData);
    if (nextProps.sTabId === sDataListTabId && nextProps.formRoute === formRoute && nextProps.formData.length > 0) {
      if (loading) {
        this.setState({ loading: true });
        return;
      }
      if (dataList.returnType !== undefined && dataList.returnType === 'CUD') {
        if (sId !== undefined && sId !== '') {
          this.setState({ sId });
        }
        /* 保存后gyCards,hiddenProcess置空 */
        this.setState({ disabled: dataList.disabled, gyCards: [], hiddenProcess: [] });
        this.handleRefresh(sId);
        return;
      }
      /* 窗体显示配置 */
      const masterShowConfig = commonFunc.getConfigCondition(masterConfig.gdsconfigformslave, 'bVisible');
      if (this.state.sActiveId === '') {
        const workOrderPan = nextProps.app.currentPane;
        /* 获取工具栏, 主表，页签标题 */
        this.setState({ toolProps: nextProps });
        const { formData, gdsjurisdiction } = urlData;
        /* 窗体配置 */
        const mainTable = formData.filter(item => (item.sTbName.toLowerCase() === 'mftworkordermaster'))[0];
        /* 匹配主表 */
        const mainConfig = mainTable.gdsconfigformslave;
        const tabProduct = mainConfig.filter(item => (item.sControlName.toLowerCase() === 'tabproduct'))[0];
        const tabPrint = mainConfig.filter(item => (item.sControlName.toLowerCase() === 'tabprint'))[0];
        const tabMaterial = mainConfig.filter(item => (item.sControlName.toLowerCase() === 'tabmaterial'))[0];
        const tabJigsaw = mainConfig.filter(item => (item.sControlName.toLowerCase() === 'tabjigsaw'))[0];
        const tabBind = mainConfig.filter(item => (item.sControlName.toLowerCase() === 'tabbind'))[0];
        /* 从表配置 */
        this.setState({
          gdsformconst,
          gdsjurisdiction,
          formData,
          mainTable,
          tabProduct: tabProduct !== undefined ? tabProduct : { showName: '产品信息', sId: new Date().getTime() + 1 }, /* 页签名 */
          tabPrint: tabPrint !== undefined ? tabPrint : { showName: '印刷信息', sId: new Date().getTime() + 2 },
          tabMaterial: tabMaterial !== undefined ? tabMaterial : { showName: '材料信息', sId: new Date().getTime() + 3 },
          tabJigsaw: tabJigsaw !== undefined ? tabJigsaw : { showName: '拼版信息', sId: new Date().getTime() + 3 },
          tabBind: tabBind !== undefined ? tabBind : { showName: '装订信息', sId: new Date().getTime() + 3 },
          mainConfig,
          disabled: workOrderPan.disabled !== undefined ? workOrderPan.disabled : false,
          sId: workOrderPan.checkedId !== undefined ? workOrderPan.checkedId : '',
          sActiveId: formId,
          sTabId: nextProps.sTabId,
          sFilterOrderBy: workOrderPan.sFilterOrderBy,
          bFilter: workOrderPan.bFilter,
          currentData: workOrderPan.currentData,
          sListFormmasterId: workOrderPan.sListFormmasterId,
          pageSize: workOrderPan.pageSize,
          pages: workOrderPan.pages,
          currentIndex: workOrderPan.newKey !== undefined ? workOrderPan.newKey.split('-')[workOrderPan.newKey.split('-').length - 1] : '',
        });
        if (workOrderPan.copyToData !== undefined && Object.keys(workOrderPan.copyToData).length > 0) {
          const copyToData = JSON.parse(JSON.stringify(workOrderPan.copyToData));
          let masterData = {}; /* 主表数据 */
          let masterSlaveData = []; /* 第一个从表数据 */
          let masterSlaveData2 = []; /* 第二个从表数据 */
          let masterSlaveData3 = []; /* 第三个从表数据 */
          let masterSlaveData4 = []; /* 第四个从表数据 */
          let newIdCount = 0;
          for (const value of Object.keys(copyToData)) {
            /* 是否数组 */
            if (!Array.isArray(copyToData[value])) {
              copyToData[value].sId = '';
              masterData = copyToData[value];
            } else if (value === 'masterSlaveData') {
              for (const v of copyToData.masterSlaveData) {
                v.handleType = 'add';
                newIdCount += 1;
              }
              masterSlaveData = copyToData[value];
            } else if (value === 'masterSlaveData2') {
              for (const v of copyToData.masterSlaveData2) {
                v.handleType = 'add';
                newIdCount += 1;
              }
              masterSlaveData2 = copyToData[value];
            } else if (value === 'masterSlaveData3') {
              for (const v of copyToData.masterSlaveData2) {
                v.handleType = 'add';
                newIdCount += 1;
              }
              masterSlaveData3 = copyToData[value];
            } else if (value === 'masterSlaveData4') {
              for (const v of copyToData.masterSlaveData2) {
                v.handleType = 'add';
                newIdCount += 1;
              }
              masterSlaveData4 = copyToData[value];
            }
          }
          /* 任何页面复制到生产施工单从表的顺序都必须是；从表、控制表、材料表、工序表 */
          this.setState({
            workOrderData: masterData, workSlaveData: masterSlaveData, workOrderJigSawData: masterSlaveData2, workOrderMaterialData: masterSlaveData3, workOrderPrintData: masterSlaveData4, newIdlength: newIdCount,
          });
          this.handleSelectChange(null, 'Map', 'workOrderData', null, 'sProductId', masterData.sProductClassifyId, formId, masterConfig);
        }
        this.setState({ masterConfig, masterShowConfig });
      } else if (dataList.returnType !== undefined && dataList.returnType === 'data'
        && dataList.componentName.indexOf('workorderslave') <= -1
        && dataList.componentName.indexOf('workordermaterial') <= -1
        && dataList.componentName.indexOf('workorderjigsaw') <= -1
        && dataList.componentName.indexOf('workorderprint') <= -1) {
        const workOrderData = Object.keys(urlData).length > 0
          ? urlData[0] : {};
        const { bCheck } = workOrderData;
        let { selectStatus } = this.state;
        if (bCheck === true) {
          selectStatus = false;
        } else {
          selectStatus = true;
        }
        this.setState({
          selectStatus, workOrderData, loading: false, sTabId: nextProps.sTabId,
        });
      } else if (newIds !== undefined && newIds.length > 0) {
        const {
          workSlaveData, workOrderMaterialData, workOrderPrintData, workOrderJigSawData, hiddenProcess,
        } = this.state;
        const ids = newIds;
        let copyToFlag = true;
        for (const item of workSlaveData) {
          if (item.sId !== undefined && item.sId.startsWith('x')) {
            copyToFlag = false;
          }
        }
        if (copyToFlag) {
          /* 此处为复制到数据处理 */
          for (const v of workSlaveData) {
            [v.sId] = ids;
            ids.splice(0, 1);
          }
          for (const v of workOrderMaterialData) {
            [v.sId] = ids;
            ids.splice(0, 1);
          }
          for (const v of workOrderPrintData) {
            [v.sId] = ids;
            ids.splice(0, 1);
          }
          for (const v of workOrderJigSawData) {
            [v.sId] = ids;
            ids.splice(0, 1);
          }
          for (const v of hiddenProcess) {
            [v.sId] = ids;
            ids.splice(0, 1);
          }
          this.setState({
            workSlaveData, workOrderMaterialData, workOrderPrintData, workOrderJigSawData, hiddenProcess, newIdlength: 0, newIdFlag: false,
          });
        } else {
          /* 此处为生成数据处理 */
          let jigSawDataId = '';
          /* 控制表 */
          for (const v of workOrderJigSawData) {
            if (v.sId !== undefined && v.sId.startsWith('x')) {
              [v.sId] = ids;
              [jigSawDataId] = ids;
              ids.splice(0, 1);
            }
          }
          for (const v of workSlaveData) {
            if (v.sId !== undefined && v.sId.startsWith('x')) {
              [v.sId] = ids;
              ids.splice(0, 1);
            }
          }
          /*  */
          for (const v of workOrderMaterialData) {
            if (v.sId !== undefined && v.sId.startsWith('x')) {
              [v.sId] = ids;
              v.sControlId = jigSawDataId;
              ids.splice(0, 1);
            }
          }
          for (const v of workOrderPrintData) {
            if (v.sId !== undefined && v.sId.startsWith('x')) {
              [v.sId] = ids;
              v.sControlId = jigSawDataId;
              ids.splice(0, 1);
            }
          }
          /* 非印刷工艺数据newId处理 */
          for (const v of hiddenProcess) {
            if (v.sId !== undefined && v.sId.startsWith('x')) {
              [v.sId] = ids;
              v.sControlId = jigSawDataId;
              ids.splice(0, 1);
            }
          }
          this.setState({
            workSlaveData, workOrderMaterialData, workOrderPrintData, workOrderJigSawData, hiddenProcess,
          });
        }
      }
      if (dataList.returnType !== undefined && dataList.returnType === 'data' && dataList.componentName === 'workorderslave') {
        const workSlaveData = Object.keys(urlData).length > 0
          ? urlData : [];
        this.setState({ workSlaveData, loading: false });
      } else if (dataList.returnType !== undefined && dataList.returnType === 'data' && dataList.componentName === 'workordermaterial') {
        const workOrderMaterialData = Object.keys(urlData).length > 0
          ? urlData : [];
        this.setState({ workOrderMaterialData, loading: false });
      } else if (dataList.returnType !== undefined && dataList.returnType === 'data' && dataList.componentName === 'workorderprint') {
        const workOrderPrintData = Object.keys(urlData).length > 0
          ? urlData : [];
        /* 非印刷工序的数据隐藏不显示 */
        const hiddenProcess = [];
        const workOrderPrintShowData = [];
        for (const item of workOrderPrintData) {
          if (item.sType === '1') {
            workOrderPrintShowData.push(item);
          } else {
            hiddenProcess.push(item);
          }
        }
        this.setState({ workOrderPrintData: workOrderPrintShowData, hiddenProcess, loading: false });
      } else if (dataList.returnType !== undefined && dataList.returnType === 'data' && dataList.componentName === 'workorderjigsaw') {
        const workOrderJigSawData = Object.keys(urlData).length > 0
          ? urlData : [];
        this.setState({ workOrderJigSawData, loading: false });
      }
    }
  }

  shouldComponentUpdate(nextProps, nextState) {
    let flag = true;
    /* 追加弹出框数值回填放行判断ppopupPane */
    if (nextProps.sTabId === nextProps.app.currentPane.key || ((nextProps.app.ppopupPane !== undefined
        && nextProps.app.ppopupPane.mainConfig !== undefined)
      ? nextProps.sTabId === nextProps.app.ppopupPane.mainConfig.key : false)) {
      if (nextState.disabled !== this.state.disabled) {
        return true;
      }
      flag = true;
    } else {
      flag = false;
    }
    return flag;
  }

  /* 数据自动变更 */
  handleFormChange = (value) => {
    const key = Object.keys(value)[0];
    const { workOrderData } = this.state;
    const { masterShowConfig } = this.state;
    const showConfig = masterShowConfig.filter(item => (item.sName === key))[0];
    if (showConfig !== undefined && showConfig.sDropDownType === 'sql') return;
    /* 数据处理,手动清空数据时数据会为undefined，不符合数据赋值要求 */
    const changeValue = commonFunc.changeValue(value);
    this.setState({
      workOrderData: { ...workOrderData, ...changeValue },
    });
  };

  /* 弹窗面板状态更改 */
  handleModalPane = (value) => {
    this.setState({ modalVisible: value.modalVisible });
  };

  /* 刷新 */
  handleRefresh = (newsId) => {
    const { dispatch } = this.props;
    const {
      masterConfig, sId, sActiveId, formData,
    } = this.state;
    let id = sId;
    if (newsId !== undefined && newsId !== '') {
      id = newsId;
    }
    if (id !== undefined && id !== '') {
      /* 表Id */
      const mainId = masterConfig.sId;
      /* 业务数据Id */
      const value = { sId: id };
      const sTabId = this.props.app.currentPane.key;
      /* 从表value */
      const slaveValue = {
        sSqlCondition: {
          sParentId: id,
        },
      };
      const mftworkorderslaveConfig = formData.filter(item => (item.sTbName === 'mftworkorderslave'))[0];
      const mftworkordercontrolConfig = formData.filter(item => (item.sTbName === 'mftworkordercontrol'))[0];
      const mftworkordermaterialsConfig = formData.filter(item => (item.sTbName === 'mftworkordermaterials'))[0];
      const mftworkorderprocessConfig = formData.filter(item => (item.sTbName === 'mftworkorderprocess'))[0];
      const mftworkorderslavesId = mftworkorderslaveConfig.sId;
      const mftworkordercontrolsId = mftworkordercontrolConfig.sId;
      const mftworkordermaterialssId = mftworkordermaterialsConfig.sId;
      const mftworkorderprocesssId = mftworkorderprocessConfig.sId;
      const mainDataUrl = `${config.server_host}business/getBusinessDataByFormcustomId/${mainId}?sModelsId=${sActiveId}`;
      dispatch({
        type: 'content/getUrlPostData',
        payload: {
          url: mainDataUrl, sTabId, componentName: 'workordermaster', value, formRoute: '/workorder', returnType: 'data',
        },
      });
      const mftworkorderslaveUrl = `${config.server_host}business/getBusinessDataByFormcustomId/${mftworkorderslavesId}?sModelsId=${sActiveId}`;
      dispatch({
        type: 'content/getUrlPostData',
        payload: {
          url: mftworkorderslaveUrl, sTabId, componentName: 'workorderslave', value: slaveValue, formRoute: '/workorder', returnType: 'data',
        },
      });
      const mftworkordercontrolUrl = `${config.server_host}business/getBusinessDataByFormcustomId/${mftworkordercontrolsId}?sModelsId=${sActiveId}`;
      dispatch({
        type: 'content/getUrlPostData',
        payload: {
          url: mftworkordercontrolUrl, sTabId, componentName: 'workorderjigsaw', value: slaveValue, formRoute: '/workorder', returnType: 'data',
        },
      });
      const mftworkordermaterialsUrl = `${config.server_host}business/getBusinessDataByFormcustomId/${mftworkordermaterialssId}?sModelsId=${sActiveId}`;
      dispatch({
        type: 'content/getUrlPostData',
        payload: {
          url: mftworkordermaterialsUrl, sTabId, componentName: 'workordermaterial', value: slaveValue, formRoute: '/workorder', returnType: 'data',
        },
      });
      const mftworkorderprocessUrl = `${config.server_host}business/getBusinessDataByFormcustomId/${mftworkorderprocesssId}?sModelsId=${sActiveId}`;
      dispatch({
        type: 'content/getUrlPostData',
        payload: {
          url: mftworkorderprocessUrl, sTabId, componentName: 'workorderprint', value: slaveValue, formRoute: '/workorder', returnType: 'data',
        },
      });
    } else {
      /* 应清空所有组件,或刷新不做任何处理或屏蔽刷新按钮 */
    }
  };

  /* 弹窗关闭 */
  handlePpopUpPaneCancel = () => {
    /* 弹窗类型，下拉/弹窗 */
    const { modalType } = this.props.app.ppopupPane;
    /* 数据集名 */
    const { dataName } = this.props.app.ppopupPane;
    const data = this.state[`${dataName}`];
    /* 如果为下拉新增则下拉值重置为空 */
    if (modalType === 'select') {
      /* 数据集类型，对象型为Map 数组型为List */
      const { dataType } = this.props.app.ppopupPane;
      const { mainKey } = this.props.app.ppopupPane;
      /* 窗体关闭时下拉重置为空,避免下拉项停留在NEW选项 */
      if (dataType === 'Map' && data[`${mainKey}`] === '000') {
        data[`${mainKey}`] = ' ';
      } else if (dataType === 'List') {
        data.map((item) => {
          if (item.key === this.state.listRecordKey[`${dataName}Key`] && item[`${mainKey}`] === '000') {
            item[`${mainKey}`] = ' ';
          }
          return item;
        });
      }
    }
    /* 置空models中弹窗面板 */
    this.props.onRemoveModalPane({});
    /* 隐藏弹窗面板 */
    this.setState({
      modalVisible: false,
      [`${dataName}`]: data,
      listRecordKey: {
        workOrderMaterialDataKey: '', workOrderPrintDataKey: '', workSlaveDataKey: '', workOrderJigSawDataKey: '',
      },
    });
  };

  /* 生产详情面板打开 */
  handleWorkOrderPaneChange = (key) => {
    const visible = this.state.workOrderModalVisible;
    this.setState({ workOrderModalVisible: !visible, workOrderJigsawSelectKey: key });
  };
  /* 生产详情面板关闭 */
  handleWorkOrderPaneClose = () => {
    this.setState({ workOrderModalVisible: false, workOrderJigsawSelectKey: '' });
  };

  /* 保存 */
  handleSubmit() {
    const { sActiveId } = this.state;
    const { token, userinfo } = this.props.app;
    const dataUrl = `${config.server_host}business/addWorksheet?sModelsId=${sActiveId}`;
    const {
      workOrderMaterialData, workOrderJigSawData, workSlaveData, hiddenProcess,
    } = this.state;
    /* 加入不显示数据进行计算 */
    const workOrderPrintData = [...this.state.workOrderPrintData, ...hiddenProcess];
    /* 过滤出handleType数据不参与进行计算 */
    const workOrderMaterialDataDel = [];
    const workOrderPrintDataDel = [];
    const workOrderJigSawDataDel = [];
    const workSlaveDataDel = [];
    for (let i = 0; i < workOrderMaterialData.length; i += 1) {
      if (workOrderMaterialData[i].handleType === 'del') {
        workOrderMaterialDataDel.push(workOrderMaterialData[i]);
        workOrderMaterialData.splice(i, 1);
        i -= 1;
      }
    }
    workOrderPrintData.forEach((item) => {
      /* double类型赋默认0,处理数据库字段为必填 */
      for (const child of Object.keys(item)) {
        if (item[child] === undefined && child.startsWith('d')) {
          item[child] = 0;
        }
      }
    });
    /* 过滤del数据不进行计算 */
    for (let i = 0; i < workOrderPrintData.length; i += 1) {
      if (workOrderPrintData[i].handleType === 'del') {
        workOrderPrintDataDel.push(workOrderPrintData[i]);
        workOrderPrintData.splice(i, 1);
        i -= 1;
      }
    }
    for (let i = 0; i < workOrderJigSawData.length; i += 1) {
      if (workOrderJigSawData[i].handleType === 'del') {
        workOrderJigSawDataDel.push(workOrderJigSawData[i]);
        workOrderJigSawData.splice(i, 1);
        i -= 1;
      }
    }
    for (let i = 0; i < workSlaveData.length; i += 1) {
      if (workSlaveData[i].handleType === 'del') {
        workSlaveDataDel.push(workSlaveData[i]);
        workSlaveData.splice(i, 1);
        i -= 1;
      }
    }
    /* 数据ID */
    let sGuid = new Date().getTime().toString();
    if (this.state.sId !== '') {
      sGuid = this.state.sId;
    }
    for (const item of workOrderMaterialData) {
      item.sParentId = sGuid;
      item.sCalcOper = userinfo.sUserName;
      item.handleType = 'add';
    }
    for (const item of workOrderPrintData) {
      item.sParentId = sGuid;
      item.sCalcOper = userinfo.sUserName;
      item.handleType = 'add';
    }
    for (const item of workOrderJigSawData) {
      item.sParentId = sGuid;
      item.sCalcOper = userinfo.sUserName;
      item.handleType = 'add';
    }
    for (const item of workSlaveData) {
      item.sParentId = sGuid;
      item.sCalcOper = userinfo.sUserName;
      item.handleType = 'add';
    }
    /* 倍率 */
    const bChangeRate = 0;
    const value = {
      data: [{
        sTable: 'mftworkorderslave_tmp',
        column: workSlaveData,
      }, {
        sTable: 'mftworkorderprocess_tmp',
        column: workOrderPrintData,
      }, {
        sTable: 'mftworkordermaterials_tmp',
        column: workOrderMaterialData,
      }, {
        sTable: 'mftworkordercontrol_tmp',
        column: workOrderJigSawData,
      }],
      sClientType: '1',
      sGuid,
      bChangeRate,
    };
    const options = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        authorization: token,
      },
      body: JSON.stringify(value),
    };
    fetch(dataUrl, options).then(response => response.json()).then((json) => {
      if (json.code === 1) {
        let mftworkorderprocess = json.dataset.rows[0].mftworkorderprocess_tmp;
        let mftworkordermaterials = json.dataset.rows[0].mftworkordermaterials_tmp;
        let mftworkordercontrol = json.dataset.rows[0].mftworkordercontrol_tmp;
        let mftworkorderslave = json.dataset.rows[0].mftworkorderslave_tmp;
        /* 合并handleType为Del的数据 */
        if (workOrderPrintDataDel.length > 0) {
          mftworkorderprocess = [...mftworkorderprocess, ...workOrderPrintDataDel];
        }
        if (workOrderJigSawDataDel.length > 0) {
          mftworkordercontrol = [...mftworkordercontrol, ...workOrderJigSawDataDel];
        }
        if (workOrderMaterialDataDel.length > 0) {
          mftworkordermaterials = [...mftworkordermaterials, ...workOrderMaterialDataDel];
        }
        if (workSlaveDataDel.length > 0) {
          mftworkorderslave = [...mftworkorderslave, ...workSlaveDataDel];
        }
        const { dispatch } = this.props;
        /* 业务数据Id */
        const sTabId = this.props.app.currentPane.key;
        this.form.validateFieldsAndScroll((err, formValue) => {
          if (!err) {
            /* 调用计算 */
            const stateFormValue = this.state.workOrderData;
            const inputValue = { ...formValue, ...stateFormValue };
            const dataUrl2 = `${config.server_host}business/addUpdateDelBusinessData?sModelsId=${sActiveId}`;
            if (this.state.sId !== '') {
              inputValue.handleType = 'update';
              inputValue.sFormId = sActiveId;
              for (const item of mftworkordermaterials) {
                item.sParentId = inputValue.sId;
              }
              for (const item of mftworkorderprocess) {
                item.sParentId = inputValue.sId;
              }
              for (const item of mftworkordercontrol) {
                item.sParentId = inputValue.sId;
              }
              for (const item of mftworkorderslave) {
                item.sParentId = inputValue.sId;
              }
              const value2 = {
                data: [{
                  sTable: 'mftworkordermaster',
                  column: [inputValue],
                }, {
                  sTable: 'mftworkorderslave',
                  column: mftworkorderslave,
                }, {
                  sTable: 'mftworkorderprocess',
                  column: mftworkorderprocess,
                }, {
                  sTable: 'mftworkordermaterials',
                  column: mftworkordermaterials,
                }, {
                  sTable: 'mftworkordercontrol',
                  column: mftworkordercontrol,
                }],
                sClientType: '1',
              };
              dispatch({
                type: 'content/getUrlPostData',
                payload: {
                  url: dataUrl2, sTabId, value: value2, componentName: 'workordermaster', formRoute: '/workorder', returnType: 'CUD',
                },
              });
            } else {
              inputValue.handleType = 'add';
              const options2 = {
                method: 'GET',
                headers: {
                  'Content-Type': 'application/json',
                },
              };
              const url = `${config.server_host}getUuid`;
              fetch(url, options2).then(response => response.json()).then((json2) => {
                if (json2.code === 1) {
                  const sId = json2.dataset.rows[0];
                  inputValue.sId = sId;
                  inputValue.sFormId = sActiveId;
                  /* 把新增时获取的唯一主键放在STATE中用于成功后刷新动作 */
                  inputValue.maxBillNo = 'sBillNo';
                  for (const item of mftworkordermaterials) {
                    item.sParentId = sId;
                  }
                  for (const item of mftworkorderprocess) {
                    item.sParentId = sId;
                  }
                  for (const item of mftworkordercontrol) {
                    item.sParentId = sId;
                  }
                  for (const item of mftworkorderslave) {
                    item.sParentId = sId;
                  }
                  const value2 = {
                    data: [{
                      sTable: 'mftworkordermaster',
                      column: [inputValue],
                    }, {
                      sTable: 'mftworkorderslave',
                      column: mftworkorderslave,
                    }, {
                      sTable: 'mftworkorderprocess',
                      column: mftworkorderprocess,
                    }, {
                      sTable: 'mftworkordermaterials',
                      column: mftworkordermaterials,
                    }, {
                      sTable: 'mftworkordercontrol',
                      column: mftworkordercontrol,
                    }],
                    sClientType: '1',
                  };
                  dispatch({
                    type: 'content/getUrlPostData',
                    payload: {
                      url: dataUrl2, sTabId, value: value2, componentName: 'workordermaster', formRoute: '/workorder', returnType: 'CUD', sId,
                    },
                  });
                }
              });
            }
          } else {
            console.log('err: ', err);
          }
        });
      } else {
        message.error(json.msg);
      }
    });
  }

  /* 获取上一条下一条首条末条 */
  handleSearchData = (sValue) => {
    const { sActiveId } = this.state;
    const { token } = this.props.app;
    const {
      sListFormmasterId, sFilterOrderBy, bFilter, formData, pages, pageSize, currentIndex, currentIndexFlag,
    } = this.state;
    let currentIndexPop = currentIndexFlag ? currentIndex : ((pages.pageNum - 1) * pageSize) + Number.parseInt(currentIndex, 10);
    if (sValue === 'first') {
      currentIndexPop = 1;
    } else if (sValue === 'end') {
      currentIndexPop = pages.totalCount;
    }
    const url = `${config.server_host}business/getBusinessDataByIndex?sModelsId=${sActiveId}`;
    const arrayForm = {};
    formData.forEach((child) => {
      if (child.sSqlStr !== undefined) {
        const keys = child.sId;
        arrayForm[`${keys}`] = keys;
      }
    });
    const value = {
      sClientType: '1',
      sListFormmasterId,
      sFormmasterId: formData[0].sId,
      currentPosition: currentIndexPop,
      configureMap: arrayForm,
      sHandleType: sValue,
      iCountSum: pages.totalCount,
    };
    if (bFilter !== undefined && bFilter !== '' && Object.keys(bFilter).length > 0) {
      value.push({ bFilter });
    }
    if (sFilterOrderBy !== undefined && sFilterOrderBy !== '' && Object.keys(sFilterOrderBy).length > 0) {
      value.push({ sFilterOrderBy });
    }
    const options = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        authorization: token,
      },
      body: JSON.stringify(value),
    };
    fetch(url, options).then(response => response.json()).then((json) => {
      if (json.code === 1) {
        const values = json.dataset.rows[0];
        const currentPostion = values.currentPosition;
        formData.forEach((child) => {
          if (child.sSqlStr !== undefined) {
            const sMainId = child.sId;
            const sMainTableName = child.sTbName;
            if (sMainTableName === 'mftworkordermaster') {
              this.setState({
                workOrderData: values[sMainId][0],
                sId: values[sMainId][0].sId,
              });
            } else if (sMainTableName === 'mftworkorderslave') {
              this.setState({
                workSlaveData: values[sMainId],
              });
            } else if (sMainTableName === 'mftworkordermaterials') {
              this.setState({
                workOrderMaterialData: values[sMainId],
              });
            } else if (sMainTableName === 'mftworkorderprocess') {
              const workOrderPrintData = values[sMainId];
              /* 非印刷工序的数据隐藏不显示 */
              const hiddenProcess = [];
              const workOrderPrintShowData = [];
              for (const item of workOrderPrintData) {
                if (item.sType === '1') {
                  workOrderPrintShowData.push(item);
                } else {
                  hiddenProcess.push(item);
                }
              }
              this.setState({
                workOrderPrintData: workOrderPrintShowData,
                hiddenProcess,
              });
            } else if (sMainTableName === 'mftworkordercontrol') {
              this.setState({
                workOrderJigSawData: values[sMainId],
              });
            }
          }
        });
        this.setState({
          currentIndex: currentPostion,
          currentIndexFlag: true,
        });
      } else {
        message.error(json.msg);
      }
    });
  };

  /* 审核 */
  handleExamine = () => {
    const { sActiveId } = this.state;
    const { workOrderData, workSlaveData, gdsformconst } = this.state;
    const sToVoid = gdsformconst.filter(item => (item.sName === 'sToVoid'));
    if (workOrderData.bInvalid === true) {
      message.warning(sToVoid[0].showName);
      return;
    }
    const { token } = this.props.app;
    const url = `${config.server_host}business/doExamine?sModelsId=${sActiveId}`;
    const paramsMap = {
      iFlag: 1,
      iTmpCheck: 0,
      sFormGuid: sActiveId,
      sGuid: this.state.sId,
    };
    const value = {
      sClientType: '1',
      sProName: 'Sp_Calc_sWod',
      paramsMap,
    };
    const options = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        authorization: token,
      },
      body: JSON.stringify(value),
    };
    fetch(url, options).then(response => response.json()).then((json) => {
      if (json.code === 1) {
        const { outData } = json.dataset.rows[0].dataSet;
        if (outData[0] === undefined || outData[0] === null || outData[0] === '' || outData[0].sReturn.split('-').length < 2) {
          const checksReturnArray = outData[0].sReturn.split('-');
          if (checksReturnArray[0] !== undefined && checksReturnArray[0] !== '') {
            workOrderData.bCheck = false;
            message.error(outData[0].sReturn);
          } else if (checksReturnArray[0] === undefined || checksReturnArray[0] === '') {
            workOrderData.bCheck = true;
            message.success(json.msg);
          }
          this.setState({ workOrderData, selectStatus: false });
        } else {
          const sReturnMessage = [];
          const sReturnArray = outData[0].sReturn.split('|');
          let sCheckModelId = '';
          if ((sReturnArray.length > 1) && ((sReturnArray[0].split('-')).length > 2)) {
            [sCheckModelId] = sReturnArray;
            [, sCheckModelId] = sCheckModelId.split('-');
          }
          sReturnArray.forEach((child) => {
            const smg = child.split('-');
            const sId = smg[0];
            const sData = workSlaveData.filter(item => (item.sId === sId));
            if (sData.length > 0) {
              const sNames = sData[0].sProductId.split('[-]');
              const sName = sNames.length > 2 ? sNames[1] : '';
              const messageCheck = `${sName}-${smg[2]}`;
              sReturnMessage.push(messageCheck);
              this.setState({
                sReturnMessage,
                sCheckModelId,
              });
            }
          });
          this.handleShowModal();
        }
      } else {
        message.error(json.msg);
      }
    });
  };

  /* 审核模板不通过时的弹窗 */
  handleShowModal = () => {
    this.setState({
      visible: true,
    });
  };
  /* 消审 */
  handleCancelExamine = () => {
    const { sActiveId } = this.state;
    const { workOrderData } = this.state;
    const { token } = this.props.app;
    const url = `${config.server_host}business/doExamine?sModelsId=${sActiveId}`;
    const paramsMap = {
      iFlag: 0,
      iTmpCheck: 0,
      sFormGuid: sActiveId,
      sGuid: this.state.sId,
    };
    const value = {
      sClientType: '1',
      sProName: 'Sp_Calc_sWod',
      paramsMap,
    };
    const options = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        authorization: token,
      },
      body: JSON.stringify(value),
    };
    fetch(url, options).then(response => response.json()).then((json) => {
      if (json.code === 1) {
        const { outData } = json.dataset.rows[0].dataSet;
        if (outData[0] === undefined || outData[0] === null || outData[0] === '' || outData[0].sReturn.split('-').length < 2) {
          const checksReturnArray = outData[0].sReturn.split('-');
          if (checksReturnArray[0] !== undefined && checksReturnArray[0] !== '') {
            workOrderData.bCheck = true;
            message.error(outData[0].sReturn);
          } else if (checksReturnArray[0] === undefined || checksReturnArray[0] === '') {
            workOrderData.bCheck = false;
            message.success(json.msg);
          }
          this.setState({ workOrderData, selectStatus: true });
        }
      } else {
        message.error(json.msg);
      }
    });
  };

  /* 新增 */
  handleAdd= () => {
    /* Tab标签Id */
    this.setState({
      selectStatus: true,
      workOrderData: { bCheck: false, bInvalid: false },
      workSlaveData: [],
      workOrderMaterialData: [],
      workOrderPrintData: [],
      workOrderJigSawData: [],
      disabled: false,
      sId: '',
    });
  };

  /* 删除 */
  handleDel = () => {
    const onhandleOk = this.handleOk;
    const { sId } = this.state;
    const { token } = this.props.app;
    const { sActiveId } = this.state;
    confirm({
      title: '确定要删除?',
      onOk() {
        const value = {
          data: {
            sMasterTable: 'mftworkordermaster',
            sId: [sId],
            sSlaveTable: [
              {
                tableName: 'mftworkorderslave',
                relationName: 'sParentId',
              }, {
                tableName: 'mftworkorderprocess',
                relationName: 'sParentId',
              }, {
                tableName: 'mftworkordermaterials',
                relationName: 'sParentId',
              }, {
                tableName: 'mftworkordercontrol',
                relationName: 'sParentId',
              }],
          },
          sClientType: '1',
        };
        const options = {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            authorization: token,
          },
          body: JSON.stringify(value),
        };
        const url = `${config.server_host}business/delMasSlaBusinessData?sModelsId=${sActiveId}`;
        fetch(url, options).then(response => response.json()).then((json) => {
          if (json.code === 1) {
            message.success(json.msg);
            onhandleOk();
          } else {
            message.error(json.msg);
          }
        });
      },
      onCancel() {},
    });
  };

  /* 确认取消 */
  handleOk = () => {
    let lastIndex = -1;
    this.props.app.panes.forEach((pane, i) => {
      if (pane.key === this.props.app.currentPane.key) {
        lastIndex = i - 1;
      }
    });

    const panes = this.props.app.panes.filter(pane => pane.key !== this.props.app.currentPane.key);
    let currentPane;
    if (lastIndex >= 0) {
      currentPane = panes[lastIndex];
    } else if (lastIndex === -1 && panes.length > 0) {
      currentPane = panes[lastIndex + 1];
    } else {
      currentPane = { title: '', route: '', key: '0' };
    }
    this.props.onRemovePane(panes, currentPane);
  };

  handleInvalidOk = () => {
    const { workOrderData } = this.state;
    workOrderData.bInvalid = true;
    this.setState({
      workOrderData,
    });
  };

  /* 作废 */
  handleInvalid = () => {
    const onInvalidOk = this.handleInvalidOk;
    const { workOrderData, gdsformconst } = this.state;
    const sToExamineVoid = gdsformconst.filter(item => (item.sName === 'sToExamineVoid'));
    if (workOrderData.bCheck === true) {
      message.warning(sToExamineVoid[0].showName);
      return;
    }
    const { sId } = this.state;
    const { token } = this.props.app;
    const { sActiveId } = this.state;
    confirm({
      title: '确定要作废?',
      onOk() {
        const value = {
          sTableName: 'mftworkordermaster',
          sId: [sId],
          sHandleType: 'toVoid',
          sClientType: '1',
        };
        const options = {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            authorization: token,
          },
          body: JSON.stringify(value),
        };
        const url = `${config.server_host}checkModel/updatebInvalid?sModelsId=${sActiveId}`;
        fetch(url, options).then(response => response.json()).then((json) => {
          if (json.code === 1) {
            message.success(json.msg);
            onInvalidOk();
          } else {
            message.error(json.msg);
          }
        });
      },
      onCancel() {},
    });
  };

  handleInvalidCancel = () => {
    const { workOrderData } = this.state;
    workOrderData.bInvalid = false;
    this.setState({
      workOrderData,
    });
  };

  /* 取消作废 */
  handleCancelInvalid = () => {
    const onInvalidCancel = this.handleInvalidCancel;
    const { workOrderData, gdsformconst } = this.state;
    const sToVoidExamine = gdsformconst.filter(item => (item.sName === 'sToVoidExamine'));
    if (workOrderData.bCheck === true) {
      message.warning(sToVoidExamine[0].showName);
      return;
    }
    const { sId } = this.state;
    const { token } = this.props.app;
    const { sActiveId } = this.state;
    confirm({
      title: '确定要取消作废?',
      onOk() {
        const value = {
          sTableName: 'mftworkordermaster',
          sId: [sId],
          sHandleType: 'cancel',
          sClientType: '1',
        };
        const options = {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            authorization: token,
          },
          body: JSON.stringify(value),
        };
        const url = `${config.server_host}checkModel/updatebInvalid?sModelsId=${sActiveId}`;
        fetch(url, options).then(response => response.json()).then((json) => {
          if (json.code === 1) {
            message.success(json.msg);
            onInvalidCancel();
          } else {
            message.error(json.msg);
          }
        });
      },
      onCancel() {},
    });
  };
  /* 取消 */
  handleCancel =(type) => {
    const onhandleOk = this.handleOk;
    confirm({
      title: '确定要取消?',
      onOk() {
        onhandleOk(type);
      },
      onCancel() {},
    });
  };

  /* 非列表联动下拉 */
  handleSelectChange = (value, dataType, dataName, sName, productClassifyId, formId, masterConfigState) => {
    /* 数据集类型，对象型为Map 数组型为List */
    if (sName === 'sProductId') {
      const { workOrderData, masterShowConfig, sBackProcessClassifyData } = this.state;
      const { sAllPartsName } = workOrderData;
      let allPartsName = [];
      if (sAllPartsName !== undefined) {
        allPartsName = sAllPartsName.split(',');
      }
      if (allPartsName.length > 0 && masterShowConfig.filter(item => item.sName === `sMaterialsName${allPartsName[0]}`).length > 0 &&
        (sBackProcessClassifyData !== '' && sBackProcessClassifyData.length > 0 &&
        masterShowConfig.filter(item => item.sName === `${sBackProcessClassifyData[0].sId}${allPartsName[0]}`).length > 0)) {
        let iIndex;
        allPartsName.forEach((sPartsName) => {
          iIndex = masterShowConfig.findIndex(item => item.sName === `dSumPQty${sPartsName}`);
          if (iIndex > -1) {
            masterShowConfig.splice(iIndex, 1);
          }
          iIndex = masterShowConfig.findIndex(item => item.sName === `sMaterialsName${sPartsName}`);
          if (iIndex > -1) {
            masterShowConfig.splice(iIndex, 1);
          }
          iIndex = masterShowConfig.findIndex(item => item.sName === `iPrintModePo${sPartsName}`);
          if (iIndex > -1) {
            masterShowConfig.splice(iIndex, 1);
          }
          iIndex = masterShowConfig.findIndex(item => item.sName === `iPositiveColor${sPartsName}`);
          if (iIndex > -1) {
            masterShowConfig.splice(iIndex, 1);
          }

          if (sBackProcessClassifyData !== '') {
            sBackProcessClassifyData.filter(processClassify => processClassify.sType !== '3').forEach((processClassify) => {
              iIndex = masterShowConfig.findIndex(item => item.sName === processClassify.sId + sPartsName);
              if (iIndex > -1) {
                masterShowConfig.splice(iIndex, 1);
              }
            });
          }
        });
        if (sBackProcessClassifyData !== '') {
          sBackProcessClassifyData.filter(processClassify => processClassify.sType === '3').forEach((processClassify) => {
            iIndex = masterShowConfig.findIndex(item => item.sName === processClassify.sId);
            if (iIndex > -1) {
              masterShowConfig.splice(iIndex, 1);
            }
          });
        }
      }
    }

    if (value !== null) {
      const data = this.state[`${dataName}`];
      if (dataType === 'Map') {
        for (const item of value) {
          data[`${item.key}`] = item.value;
        }
        if (sName === 'sProductId') {
          this.setState({ sBackProcessClassifyData: [], [`${dataName}`]: data });
        } else {
          this.setState({ [`${dataName}`]: data });
        }
      }
    }

    if (sName === 'sProductId') {
      const { token } = this.props.app;
      let sActiveId;
      let masterConfig;
      let sProductClassifyId;
      if (value !== null) {
        sActiveId = { ...this.state.sActiveId };
        masterConfig = { ...this.state.masterConfig };
        sProductClassifyId = value !== undefined && value.length > 0 &&
        value.filter(item => item.key === 'sProductClassifyId').length > 0 ?
          value.filter(item => item.key === 'sProductClassifyId')[0].value : '';
      } else {
        sProductClassifyId = productClassifyId;
        sActiveId = formId;
        masterConfig = masterConfigState;
      }
      if (sProductClassifyId === undefined || sProductClassifyId === '') {
        return;
      }

      const sBackProcessClassify = masterConfig.gdsconfigformslave.filter(item => (item.sName.toLowerCase() === 'sbackprocessclassify'))[0];
      const url = `${config.server_host}business/getSelectDataBysControlId/${sBackProcessClassify.sId}?sModelsId=${sActiveId}`;
      const values = {
        sKeyUpFilterName: '',
        sSqlCondition: { sProductClassifyId },
      };
      const options = {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          authorization: token,
        },
        body: JSON.stringify(values),
      };

      fetch(url, options).then(response => response.json()).then((json) => {
        if (json.code === 1) {
          const { rows } = json.dataset;
          this.setState({ sBackProcessClassifyData: rows, gyCards: [] });
        }
      });
    }
  };

  handleForm = (form) => {
    this.form = form;
  };

  /* 从表表单自动变更 */
  handleProductData = (value) => {
    const value2 = commonFunc.replaceSelectMasterData(value, this.state.workOrderData);
    const workSlaveDataState = [...this.state.workSlaveData];
    const workSlaveDataDel = workSlaveDataState.filter(item => (item.handleType === 'del'));
    const workSlaveData = [...workSlaveDataDel, ...value2];
    let sumCount = 0;
    for (const item of workSlaveData) {
      if (item.dProductQty !== undefined) {
        sumCount += item.dProductQty;
      }
    }
    const { workOrderJigSawData } = this.state;
    /* 产品数量更改改变部件数量，部件数量为产品数量总和 */
    if (sumCount > 0) {
      for (const item of workOrderJigSawData) {
        item.dPartsQty = sumCount;
      }
    }
    this.setState({
      workSlaveData,
      workOrderJigSawData,
    });
  };
  /* 外部打印表单自动变更 */
  handleOutPrintData=(value) => {
    const value2 = commonFunc.replaceSelectMasterData(value, this.state.workOrderData);
    /* 由外部获取到的数据没有隐藏工序也不包含del数据 */
    const workOrderPrintDataState = this.state.workOrderPrintData;
    for (const item of value2) {
      const index = workOrderPrintDataState.findIndex(child => (child.key === item.key));
      if (index > -1) {
        workOrderPrintDataState.splice(index, 1);
        workOrderPrintDataState.push(item);
      }
    }
    this.setState({ workOrderPrintData: workOrderPrintDataState });
  };

  /* 弹出打印表单自动变更 */
  handlePrintData = (value) => {
    const value2 = commonFunc.replaceSelectMasterData(value, this.state.workOrderData);
    const workOrderPrintDataState = this.state.workOrderPrintData.filter(item => (item.handleType !== 'del'));
    const workOrderPrintDataDel = this.state.workOrderPrintData.filter(item => (item.handleType === 'del'));
    let workOrderPrintDataOther = [];
    let workOrderSelectedControlMap = {};
    const { hiddenProcess } = this.state;
    for (const child of hiddenProcess) {
      if (child.key === undefined) {
        child.key = child.sId;
      }
    }
    if (this.state.workOrderJigsawSelectKey !== undefined && this.state.workOrderJigsawSelectKey !== '') {
      [workOrderSelectedControlMap] = this.state.workOrderJigSawData.filter(item => (item.key !== undefined ? item.key === this.state.workOrderJigsawSelectKey : item.sId === this.state.workOrderJigsawSelectKey));
      /* 弹窗详情下修改需要保留所有数据 */
      workOrderPrintDataOther = workOrderPrintDataState.filter(item => (item.sControlId !== this.state.workOrderJigsawSelectKey && item.sType !== '3'));
      /* 合并非该控制表的隐藏数据 */
      const hiddenData = hiddenProcess.filter(item => (item.sControlId !== this.state.workOrderJigsawSelectKey && item.sType !== '3'));
      workOrderPrintDataOther = [...workOrderPrintDataOther, ...hiddenData];
    }
    for (const child of value2) {
      if ((child.sControlId === undefined || child.sControlId === '') && this.state.workOrderJigsawSelectKey !== undefined && this.state.workOrderJigsawSelectKey !== '') {
        child.sControlId = this.state.workOrderJigsawSelectKey;
        child.sPartsName = workOrderSelectedControlMap.sPartsName;
      } else if (child.sControlId !== undefined && child.sType === '3') {
        child.sControlId = '';
        child.sPartsName = '';
      }
    }
    const workOrderPrintData = [...workOrderPrintDataOther, ...value2];
    /* 去除详情里面的隐藏工序 */
    const newHiddenProcess = [];
    let i = 0;
    while (i < workOrderPrintData.length) {
      if (hiddenProcess.length > 0) {
        const workOrderPrintDataMap = JSON.parse(JSON.stringify(workOrderPrintData[i]));
        /* 该条数据匹配隐藏工序中的对象 */
        const printMap = hiddenProcess.filter(item => ((workOrderPrintDataMap.key !== undefined && item.key === workOrderPrintDataMap.key) || (workOrderPrintDataMap.sId !== undefined && item.key === workOrderPrintDataMap.sId)))[0];
        if ((workOrderPrintDataMap.key !== undefined && printMap !== undefined && workOrderPrintDataMap.key === printMap.key) || (workOrderPrintDataMap.sId !== undefined && printMap !== undefined && workOrderPrintDataMap.sId === printMap.key)) {
          newHiddenProcess.push(workOrderPrintDataMap);
          workOrderPrintData.splice(i, 1);
          i -= 1;
        }
      }
      i += 1;
    }
    this.setState({
      workOrderPrintData: [...workOrderPrintData, ...workOrderPrintDataDel],
      hiddenProcess: newHiddenProcess,
    });
  };
  /* 材料表单自动变更 */
  handleMaterialData = (value) => {
    const value2 = commonFunc.replaceSelectMasterData(value, this.state.workOrderData);
    const workOrderMaterialDataState = [...this.state.workOrderMaterialData];
    let workOrderMaterialDataDel = [];
    let workOrderSelectedControlMap = {};
    if (this.state.workOrderJigsawSelectKey !== undefined && this.state.workOrderJigsawSelectKey !== '') {
      [workOrderSelectedControlMap] = this.state.workOrderJigSawData.filter(item => (item.key !== undefined ? item.key === this.state.workOrderJigsawSelectKey : item.sId === this.state.workOrderJigsawSelectKey));
      /* 弹窗详情下修改需要保留所有数据 */
      workOrderMaterialDataDel = workOrderMaterialDataState.filter(item => (item.sControlId !== this.state.workOrderJigsawSelectKey && item.sType !== '2'));
    } else {
      /* 非弹窗详情下修改过滤del数据 */
      workOrderMaterialDataDel = workOrderMaterialDataState.filter(item => (item.handleType === 'del'));
    }
    for (const child of value2) {
      if ((child.sControlId === undefined || child.sControlId === '') && this.state.workOrderJigsawSelectKey !== undefined && this.state.workOrderJigsawSelectKey !== '') {
        child.sControlId = this.state.workOrderJigsawSelectKey;
        child.sPartsName = workOrderSelectedControlMap.sPartsName;
      } else if (child.sControlId !== undefined && child.sType === '2') {
        child.sControlId = '';
        child.sPartsName = '';
      }
    }
    const workOrderMaterialData = [...workOrderMaterialDataDel, ...value2];
    this.setState({
      workOrderMaterialData,
    });
  };

  /* 拼版表单自动变更 */
  handleJigSawData = (value) => {
    const value2 = commonFunc.replaceSelectMasterData(value, this.state.workOrderData);
    const workOrderJigSawDataState = [...this.state.workOrderJigSawData];
    const { workSlaveData } = this.state;
    const workOrderJigSawDataDel = workOrderJigSawDataState.filter(item => (item.handleType === 'del'));
    const workOrderJigSawData = [...workOrderJigSawDataDel, ...value2];
    const { workOrderMaterialData, workOrderPrintData } = this.state;
    let sumCount = 0;
    for (const item of workSlaveData) {
      if (item.dProductQty !== undefined) {
        sumCount += item.dProductQty;
      }
    }
    for (const item of workOrderJigSawData) {
      /* 部件数量为产品数量之和 */
      if (sumCount > 0) {
        item.dPartsQty = sumCount;
      }
      for (const child of workOrderMaterialData) {
        if (child.sControlId === item.sId || child.sControlId === item.key) {
          child.sPartsName = item.sPartsName;
        }
      }
      for (const child of workOrderPrintData) {
        if (child.sControlId === item.sId || child.sControlId === item.key) {
          child.sPartsName = item.sPartsName;
        }
      }
    }
    this.setState({
      workOrderJigSawData,
      workOrderMaterialData,
      workOrderPrintData,
    });
  };

  /* 详情页拼版自动变更 */
  handlePpopJigSawData = (value) => {
    const { workOrderJigSawData } = this.state;
    let workOrderJigSawMap = '';
    for (let i = 0; i < workOrderJigSawData.length; i += 1) {
      if (workOrderJigSawData[i].key === this.state.workOrderJigsawSelectKey || workOrderJigSawData[i].sId === this.state.workOrderJigsawSelectKey) {
        workOrderJigSawMap = workOrderJigSawData[i];
        workOrderJigSawData.splice(i, 1);
      }
    }
    workOrderJigSawMap = { ...workOrderJigSawMap, ...value };
    workOrderJigSawData.push(workOrderJigSawMap);
    this.setState({ workOrderJigSawData });
  };

  /* 用于返回列表编辑框弹窗所属行主键 */
  handleRecordKey = (value) => {
    const { listRecordKey } = this.state;
    this.setState({ listRecordKey: { ...listRecordKey, ...value } });
  };

  /* 修改 */
  handleEdit = (obj) => {
    const { disabled } = obj;
    const { workOrderData, gdsformconst } = this.state;
    const sToVoidEdit = gdsformconst.filter(item => (item.sName === 'sToVoidEdit'));
    const sToExamineEdit = gdsformconst.filter(item => (item.sName === 'sToExamineEdit'));
    if (workOrderData.bInvalid === true) {
      message.warning(sToVoidEdit[0].showName);
      return;
    }
    if (workOrderData.bCheck === true) {
      message.warning(sToExamineEdit[0].showName);
      return;
    }
    this.setState({ disabled, selectStatus: true });
  };

  /* 数据生成按钮 */
  handleDataCreate= () => {
    const { workOrderData, formData, gyCards } = this.state;
    const { token } = this.props.app;
    const paramMap = {};
    const { sAllPartsName } = workOrderData;
    let allPartsName = [];
    if (sAllPartsName !== undefined) {
      allPartsName = sAllPartsName.split(',');
    }
    let cpProcessName = '';
    // paramMap.modelName = workOrderData.modelName;
    paramMap.sProductClassifyId = workOrderData.sProductClassifyId;
    paramMap.sProductId = workOrderData.sProductId;
    paramMap.sProductStyleId = workOrderData.sProductStyleId;
    paramMap.sProductStyle = workOrderData.sProductStyle;
    paramMap.dProductWidth = workOrderData.sProductStyle.split('*').length > 0 ? workOrderData.sProductStyle.split('*')[1] : 0;
    paramMap.dProductLength = workOrderData.sProductStyle.split('*').length > 0 ? workOrderData.sProductStyle.split('*')[0] : 0;
    paramMap.dProductHeight = 0;
    paramMap.dProductQty = workOrderData.dProductQty;
    const partsInfo = [];
    allPartsName.forEach((item) => {
      const partInfo = {};
      partInfo.sPartsName = item;
      partInfo.dPartsQty = workOrderData.dProductQty;
      partInfo.dSumPQty = workOrderData[`dSumPQty${item}`];
      const materialsInfo = [];
      const material = {};
      material.sMaterialsId = workOrderData[`sMaterialsId${item}`];
      material.sMaterialsNo = workOrderData[`sMaterialsNo${item}`];
      material.sMaterialsName = workOrderData[`sMaterialsName${item}`] !== undefined && workOrderData[`sMaterialsName${item}`].split('[-]').length > 1 ? workOrderData[`sMaterialsName${item}`].split('[-]')[1] : workOrderData[`sMaterialsName${item}`];
      materialsInfo.push(material);
      partInfo.materialsInfo = materialsInfo;
      partInfo.iPositiveColor = workOrderData[`iPositiveColor${item}`];
      partInfo.iPrintModePo = workOrderData[`iPrintModePo${item}`];
      if (material.sMaterialsId !== undefined && material.sMaterialsId !== '') {
        const processInfo = [];
        gyCards.filter(card => card.sPartsName === item && card.sType !== '3').forEach((card) => {
          const process = {};
          process.sProductClassifyId = card.sId;
          process.sProcessId = workOrderData[card.sId + item];
          if (workOrderData[card.sId + card.sName + item] !== undefined) {
            process.sProcessName = workOrderData[card.sId + card.sName + item];
            process.sType = workOrderData[card.sId + card.sType + item];
            processInfo.push(process);
          }
        });
        partInfo.processInfo = processInfo;
        partsInfo.push(partInfo);
      }
    });
    const productProcessInfo = [];
    gyCards.filter(card => card.sType === '3').forEach((card) => {
      const process = {};
      process.sProductClassifyId = card.sId;
      process.sProcessId = workOrderData[card.sId];
      process.sProcessName = workOrderData[card.sId + card.sName];
      if (workOrderData[card.sId + card.sName] !== undefined) {
        cpProcessName = cpProcessName === '' ? workOrderData[card.sId + card.sName] : `${cpProcessName},${workOrderData[card.sId + card.sName]}`;
        productProcessInfo.push(process);
      }
    });
    paramMap.cpProcessName = cpProcessName;
    paramMap.productProcessInfo = productProcessInfo;
    paramMap.partsInfo = partsInfo;
    let url = `${config.server_host}calculationStd/countMoney`;
    const options = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        authorization: token,
      },
      body: JSON.stringify(paramMap),
    };
    fetch(url, options).then(response => response.json()).then((json) => {
      if (json.code === 1) {
        const { rows } = json.dataset;
        const workSlaveData = [];
        const workOrderMaterialData = [];
        const workOrderPrintData = [];
        const workOrderJigSawData = [];
        const mftworkorderslaveConfig = formData.filter(item => (item.sTbName === 'mftworkorderslave'))[0];
        // const mftworkordercontrolConfig = formData.filter(item => (item.sTbName === 'mftworkordercontrol'))[0];
        const mftworkordermaterialsConfig = formData.filter(item => (item.sTbName === 'mftworkordermaterials'))[0];
        const mftworkorderprocessConfig = formData.filter(item => (item.sTbName === 'mftworkorderprocess'))[0];
        const workSlaveMap = {};
        // const workordercontrolMap = {};
        // const workordermaterialsMap = {};
        const printNewCount = 0;
        const hiddenProcess = [];/* 非印刷工艺不显示 */
        for (const item of mftworkorderslaveConfig.gdsconfigformslave) {
          workSlaveMap[`${item.sName}`] = workOrderData[`${item.sName}`];
        }
        workSlaveMap.sId = `${Date.now()}${uuid.v4()}`;
        workSlaveMap.handleType = 'add';
        workSlaveData.push(workSlaveMap);
        rows[0].partsNewInfo.forEach((partInfo, iIndex) => {
          const workordercontrolMap = {};
          for (const child of Object.keys(partInfo)) {
            workordercontrolMap[child] = partInfo[child];
          }
          workordercontrolMap.handleType = 'add';
          workordercontrolMap.sId = `${Date.now()}${uuid.v4()}`;
          workordercontrolMap.iIncrement = null;
          workordercontrolMap.iOrder = iIndex;
          workOrderJigSawData.push(workordercontrolMap);
          // 材料信息
          partInfo.materialsInfo.forEach((materialInfo, iOrder) => {
            const workordermaterialsMap = {};
            for (const item of mftworkordermaterialsConfig.gdsconfigformslave) {
              workordermaterialsMap[`${item.sName}`] = materialInfo[`${item.sName}`];
            }
            workordermaterialsMap.handleType = 'add';
            workordermaterialsMap.sType = '0';
            workordermaterialsMap.iPartOrder = iIndex;
            workordermaterialsMap.iOrder = iOrder;
            workordermaterialsMap.sPartsName = workordercontrolMap.sPartsName;
            workordermaterialsMap.sControlId = workordercontrolMap.sId;
            workordermaterialsMap.sId = `${Date.now()}${uuid.v4()}`;
            workOrderMaterialData.push(workordermaterialsMap);
          });
          // 工序信息
          const workorderprintMap = {};
          workorderprintMap.handleType = 'add';
          workorderprintMap.sProcessId = partInfo.sProcessId;
          workorderprintMap.sType = partInfo.sType;
          workorderprintMap.iPartOrder = iIndex;
          workorderprintMap.iOrder = 1;
          workorderprintMap.sProcessName = partInfo.sProcessName;
          workorderprintMap.sPartsName = workordercontrolMap.sPartsName;
          workorderprintMap.sControlId = workordercontrolMap.sId;
          workorderprintMap.dProcessInQty = partInfo.dProcessInQty;
          workorderprintMap.dLossQty = partInfo.dLossQty;
          workorderprintMap.dProcessOutQty = partInfo.dProcessOutQty;
          workorderprintMap.sId = `${Date.now()}${uuid.v4()}`;
          workOrderPrintData.push(workorderprintMap);

          partInfo.processInfo.forEach((process, iOrder) => {
            const workorderprocessMap = {};
            for (const item of mftworkorderprocessConfig.gdsconfigformslave) {
              workorderprocessMap[`${item.sName}`] = process[`${item.sName}`];
            }
            for (const child of Object.keys(process)) {
              workorderprocessMap[child] = process[child];
            }
            workorderprocessMap.handleType = 'add';
            workorderprocessMap.sProcessId = process.sProcessId;
            workorderprocessMap.sType = process.sType;
            workorderprocessMap.iPartOrder = iIndex;
            workorderprocessMap.iOrder = iOrder;
            workorderprocessMap.sPartsName = workordercontrolMap.sPartsName;
            workorderprocessMap.sControlId = workordercontrolMap.sId;
            workorderprocessMap.sId = `${Date.now()}${uuid.v4()}`;
            workOrderPrintData.push(workorderprocessMap);
          });
        });
        rows[0].productProcessInfo.forEach((process, iOrder) => {
          const workorderprocessMap = {};
          for (const item of mftworkorderprocessConfig.gdsconfigformslave) {
            workorderprocessMap[`${item.sName}`] = process[`${item.sName}`];
          }
          for (const child of Object.keys(process)) {
            workorderprocessMap[child] = process[child];
          }
          workorderprocessMap.handleType = 'add';
          workorderprocessMap.sType = '3';
          workorderprocessMap.sPartsName = '';
          workorderprocessMap.iPartOrder = 999;
          workorderprocessMap.iOrder = iOrder;
          workorderprocessMap.sId = `${Date.now()}${uuid.v4()}`;
          workOrderPrintData.push(workorderprocessMap);
        });
        workOrderPrintData.sort((g1, g2) => {
          let sPartOrder1 = `0000${g1.iPartOrder}`;
          sPartOrder1 = sPartOrder1.substring(sPartOrder1.length - 3);
          let sOrder1 = `000${g1.iOrder}`;
          sOrder1 = sOrder1.substring(sOrder1.length - 3);

          let sPartOrder2 = `0000${g2.iPartOrder}`;
          sPartOrder2 = sPartOrder2.substring(sPartOrder2.length - 3);
          let sOrder2 = `000${g2.iOrder}`;
          sOrder2 = sOrder2.substring(sOrder2.length - 3);
          return parseInt(sPartOrder1 + g1.sType + sOrder1, 10) - parseInt(sPartOrder2 + g2.sType + sOrder2, 10);
        });
        this.setState({
          workSlaveData, workOrderMaterialData, workOrderPrintData, workOrderJigSawData, hiddenProcess,
        });
        const { dispatch } = this.props;
        /* 生成数据会生成4条数据，请求4条sId */
        const sIdCount = printNewCount + 3;
        url = `${config.server_host}getUuid/${sIdCount}`;
        const { sTabId } = this.state;
        dispatch({
          type: 'content/getCopyDataId',
          payload: {
            sTabId, url, formRoute: '/workorder', componentName: 'workordermaster',
          },
        });
      }
    });
  };
  /* 勾选工艺卡 */
  handleGyChange=(e, value, sPartsName) => {
    const { gyCards } = this.state;
    const index = gyCards.findIndex(item => (item.sId === value.sId && item.sPartsName === sPartsName));
    if (e.target.checked) {
      if (index <= -1) {
        const newvalue = { ...value };
        newvalue.sPartsName = sPartsName;
        gyCards.push(newvalue);
      }
    } else if (index > -1) {
      gyCards.splice(index, 1);
    }
    this.setState({ gyCards });
  };
  /* 计算 */
  handleCalculate=() => {
    const { sActiveId } = this.state;
    const { token, userinfo } = this.props.app;
    const dataUrl = `${config.server_host}business/addWorksheet?sModelsId=${sActiveId}`;
    const {
      workOrderMaterialData, workOrderJigSawData, workSlaveData, hiddenProcess,
    } = this.state;
    /* 加入不显示数据进行计算 */
    const workOrderPrintData = [...this.state.workOrderPrintData, ...hiddenProcess];
    /* 过滤出handleType数据不参与进行计算 */
    const workOrderMaterialDataDel = [];
    const workOrderPrintDataDel = [];
    const workOrderJigSawDataDel = [];
    const workSlaveDataDel = [];
    for (let i = 0; i < workOrderMaterialData.length; i += 1) {
      if (workOrderMaterialData[i].handleType === 'del') {
        workOrderMaterialDataDel.push(workOrderMaterialData[i]);
        workOrderMaterialData.splice(i, 1);
        i -= 1;
      }
    }
    workOrderPrintData.forEach((item) => {
      /* double类型赋默认0,处理数据库字段为必填 */
      for (const child of Object.keys(item)) {
        if (item[child] === undefined && child.startsWith('d')) {
          item[child] = 0;
        }
      }
    });
    /* 过滤del数据不进行计算 */
    for (let i = 0; i < workOrderPrintData.length; i += 1) {
      if (workOrderPrintData[i].handleType === 'del') {
        workOrderPrintDataDel.push(workOrderPrintData[i]);
        workOrderPrintData.splice(i, 1);
        i -= 1;
      }
    }
    for (let i = 0; i < workOrderJigSawData.length; i += 1) {
      if (workOrderJigSawData[i].handleType === 'del') {
        workOrderJigSawDataDel.push(workOrderJigSawData[i]);
        workOrderJigSawData.splice(i, 1);
        i -= 1;
      }
    }
    workSlaveData.forEach((item) => {
      /* double类型赋默认0,处理数据库字段为必填 */
      for (const child of Object.keys(item)) {
        if (item[child] === undefined && child.startsWith('d')) {
          item[child] = 0;
        }
      }
    });
    for (let i = 0; i < workSlaveData.length; i += 1) {
      if (workSlaveData[i].handleType === 'del') {
        workSlaveDataDel.push(workSlaveData[i]);
        workSlaveData.splice(i, 1);
        i -= 1;
      }
    }
    /* 数据ID */
    let sGuid = new Date().getTime().toString();
    if (this.state.sId !== '') {
      sGuid = this.state.sId;
    }
    for (const item of workOrderMaterialData) {
      item.sParentId = sGuid;
      item.sCalcOper = userinfo.sUserName;
      item.handleType = 'add';
    }
    for (const item of workOrderPrintData) {
      item.sParentId = sGuid;
      item.sCalcOper = userinfo.sUserName;
      item.handleType = 'add';
    }
    for (const item of workOrderJigSawData) {
      item.sParentId = sGuid;
      item.sCalcOper = userinfo.sUserName;
      item.handleType = 'add';
    }
    for (const item of workSlaveData) {
      item.sParentId = sGuid;
      item.sCalcOper = userinfo.sUserName;
      item.handleType = 'add';
    }
    /* 倍率 */
    const bChangeRate = 0;
    const value = {
      data: [{
        sTable: 'mftworkorderslave_tmp',
        column: workSlaveData,
      }, {
        sTable: 'mftworkorderprocess_tmp',
        column: workOrderPrintData,
      }, {
        sTable: 'mftworkordermaterials_tmp',
        column: workOrderMaterialData,
      }, {
        sTable: 'mftworkordercontrol_tmp',
        column: workOrderJigSawData,
      }],
      sClientType: '1',
      sGuid,
      bChangeRate,
    };
    const options = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        authorization: token,
      },
      body: JSON.stringify(value),
    };
    fetch(dataUrl, options).then(response => response.json()).then((json) => {
      if (json.code === 1) {
        const mftworkorderprocess = json.dataset.rows[0].mftworkorderprocess_tmp;
        const mftworkordermaterials = json.dataset.rows[0].mftworkordermaterials_tmp;
        const mftworkordercontrol = json.dataset.rows[0].mftworkordercontrol_tmp;
        const mftworkorderslave = json.dataset.rows[0].mftworkorderslave_tmp;
        const newHiddenProcess = [];
        for (let i = 0; i < mftworkorderprocess.length; i += 1) {
          if (mftworkorderprocess[i].sType !== '1') {
            newHiddenProcess.push(mftworkorderprocess[i]);
            mftworkorderprocess.splice(i, 1);
            i -= 1;
          }
        }
        this.setState({
          workSlaveData: [...mftworkorderslave, ...workSlaveDataDel], workOrderPrintData: [...mftworkorderprocess, ...workOrderPrintDataDel], workOrderMaterialData: [...mftworkordermaterials, ...workOrderMaterialDataDel], workOrderJigSawData: [...mftworkordercontrol, ...workOrderJigSawDataDel], hiddenProcess: newHiddenProcess,
        });
      } else {
        message.error(json.msg);
      }
    });
  };

  handleCopyTo = (activeId, value) => {
    const { workOrderData, gdsformconst } = this.state;
    const sToVoidCopy = gdsformconst.filter(item => (item.sName === 'sToVoidCopy'));
    const sToCopyLimit = gdsformconst.filter(item => (item.sName === 'sToCopyLimit'));
    const sToCheckCopy = gdsformconst.filter(item => (item.sName === 'sToCheckCopy'));
    if (workOrderData.bInvalid === true) {
      message.warning(sToVoidCopy[0].showName);
      return;
    }
    if (workOrderData.bCopyLimit === true) {
      message.warning(sToCopyLimit[0].showName);
      return;
    }
    if (workOrderData.bCheck === false) {
      message.warning(sToCheckCopy[0].showName);
      return;
    }
    const { dispatch } = this.props;
    const vConfig = value;
    /* 复制过去的主表数据 */
    let masterData = {};
    /* 复制过去的从表数据 */
    let masterSlaveData = [];
    /* 复制过去的从表2数据 */
    let masterSlaveData2 = [];
    /* 复制过去的从表3数据 */
    let masterSlaveData3 = [];
    /* 复制过去的从表4数据 */
    let masterSlaveData4 = [];
    if (vConfig.length > 0) {
      const result = commonFunc.getBillCopyData(vConfig, this.state.workOrderData, this.state.workSlaveData, this.state.workOrderJigSawData, this.state.workOrderMaterialData, this.state.workOrderPrintData);
      if (result !== undefined) {
        masterData = { ...result.masterData };
        masterSlaveData = { ...result.masterSlaveData };
        masterSlaveData2 = { ...result.masterSlaveData2 };
        masterSlaveData3 = { ...result.masterSlaveData3 };
        masterSlaveData4 = { ...result.masterSlaveData4 };
      }
    }
    /* Tab标签Id */
    const paneKey = new Date().getTime().toString();
    /* 窗体Id */
    const sActiveId = activeId;
    const sNameUrl = `${config.server_host}gdsmodule/getGdsmoduleById/${sActiveId}?sModelsId=${sActiveId}`;
    dispatch({
      type: 'content/getUrlData',
      payload: {
        url: sNameUrl,
        sTabId: paneKey,
        urlDataType: 'newPane',
        disabled: false,
        sParentId: this.state.sTabId,
        copyToData: {
          masterData, masterSlaveData, masterSlaveData2, masterSlaveData3, masterSlaveData4,
        },
      },
    });
  };

  handlePrintChild = (sId) => {
    const { formData } = this.state;
    const { token } = this.props.app;
    const { sActiveId } = this.state;
    const sMainTableId = formData[0].sId;
    const queryFilter = {};
    formData.map((item) => {
      const sDataId = item.sId;
      queryFilter[sDataId] = sDataId === sMainTableId ? { sId: this.state.sId } : {
        sSqlCondition: {
          sParentId: this.state.sId,
        },
      };
    });
    const sReportId = sId;
    const queryFilterJson = escape(JSON.stringify(queryFilter));
    const urlPrint = `${config.server_host}printReport/printPdf/${sReportId}?queryFilter=${queryFilterJson}&sModelsId=${sActiveId}&sMaintableId=${sMainTableId}&token=${encodeURIComponent(token)}`;
    window.open(urlPrint);
  };

  render() {
    const { pageLoading } = this.props;
    const { props, state } = this;
    const { app } = this.props;
    const {
      visible, gdsformconst, sReturnMessage, sActiveId, sCheckModelId, workOrderData,
    } = this.state;
    const { loading } = this.state;
    return (
      <div>
        <Spin spinning={loading}>
          {pageLoading ? '' :
          <div>
            <WorderComponent
              {...props}
              {...state}
              handleAdd={this.handleAdd.bind(this)}
              handleSubmit={this.handleSubmit.bind(this)}
              handleForm={this.handleForm.bind(this)}
              onChange={this.handleFormChange.bind(this)}
              handleModalPane={this.handleModalPane.bind(this)}
              handleSelectChange={this.handleSelectChange.bind(this)}
              handleProductData={this.handleProductData.bind(this)}
              handleRecordKey={this.handleRecordKey.bind(this)}
              handlePrintData={this.handlePrintData.bind(this)}
              handleOutPrintData={this.handleOutPrintData.bind(this)}
              handleMaterialData={this.handleMaterialData.bind(this)}
              handleJigSawData={this.handleJigSawData.bind(this)}
              handleDataCreate={this.handleDataCreate.bind(this)}
              handleGyChange={this.handleGyChange.bind(this)}
              handleCalculate={this.handleCalculate.bind(this)}
              handleEdit={this.handleEdit.bind(this)}
              handleWorkOrderPaneChange={this.handleWorkOrderPaneChange.bind(this)}
              handleCopyTo={this.handleCopyTo.bind(this)}
              onExamine={this.handleExamine.bind(this)}
              onCancelExamine={this.handleCancelExamine.bind(this)}
              onNext={this.handleSearchData.bind(this, 'next')}
              onPrior={this.handleSearchData.bind(this, 'up')}
              onFirst={this.handleSearchData.bind(this, 'first')}
              onLast={this.handleSearchData.bind(this, 'end')}
              onPrintChild={this.handlePrintChild}
              onInvalid={this.handleInvalid.bind(this)}
              onCancelInvalid={this.handleCancelInvalid.bind(this)}
            />
            <CheckModel
              visible={visible}
              gdsformconst={gdsformconst}
              sReturnMessage={sReturnMessage}
              app={app}
              sActiveId={sActiveId}
              sCheckModelId={sCheckModelId}
              sTbName="mftworkordermaster"
              sBillKey="Sp_Calc_sWod"
              sBillNo={workOrderData.sBillNo}
            />
            <Modal
              title={Object.keys(this.state.modalPanel).length > 0 ? this.state.modalPanel.title : ''}
              visible={this.state.modalVisible}
              onCancel={this.handlePpopUpPaneCancel.bind(this)}
              footer={null}
              width={1000}
              wrapClassName={styles.modal}
              zIndex={1000}
            >
              <div className={styles.popupPan} id="popupPan">
                <PpopupPan handleGetResult={this.handleGetResult} />
              </div>
            </Modal>
            <Modal
              title="详情"
              visible={this.state.workOrderModalVisible}
              onCancel={this.handleWorkOrderPaneClose.bind(this)}
              footer={null}
              width={1000}
              wrapClassName={styles.modal}
              zIndex={999}
            >
              <WorkOrderPpop
                app={this.props.app}
                {...state}
                handlePpopJigSawData={this.handlePpopJigSawData.bind(this)}
                handleRecordKey={this.handleRecordKey.bind(this)}
                handleModalPane={this.handleModalPane.bind(this)}
                dataName="workOrderData_Ppop"
                dataType="Map"
              />
              <MaterialPpop
                app={this.props.app}
                {...state}
                form={this.form}
                handleMaterialData={this.handleMaterialData.bind(this)}
                handleRecordKey={this.handleRecordKey.bind(this)}
                handleModalPane={this.handleModalPane.bind(this)}
                dataName="workOrderMaterialData_Ppop"
                dataType="List"
              />
              <PrintPpop
                app={this.props.app}
                {...state}
                form={this.form}
                handlePrintData={this.handlePrintData.bind(this)}
                handleRecordKey={this.handleRecordKey.bind(this)}
                handleModalPane={this.handleModalPane.bind(this)}
                dataName="workOrderPrintData_Ppop"
                dataType="List"
              />
            </Modal>
          </div>}
        </Spin>
      </div>
    );
  }
}

const WorderComponent = Form.create({
  mapPropsToFields(props) {
    const { workOrderData, sBackProcessClassifyData, masterShowConfig } = props;
    const { sAllPartsName } = workOrderData;
    let allPartsName = [];
    if (sAllPartsName !== undefined) {
      allPartsName = sAllPartsName.split(',');
    }
    if (allPartsName.length > 0 && masterShowConfig.filter(item => item.sName === `sMaterialsName${allPartsName[0]}`).length <= 0 &&
      sBackProcessClassifyData !== '' && sBackProcessClassifyData.length > 0 &&
      masterShowConfig.filter(item => item.sName === `${sBackProcessClassifyData[0].sId}${allPartsName[0]}`).length <= 0) {
      const sumPQtyConfig = masterShowConfig.filter(item => item.sName === 'dSumPQty').length > 0 ? masterShowConfig.filter(item => item.sName === 'dSumPQty')[0] : [];
      const materialsNameConfig = masterShowConfig.filter(item => item.sName === 'sMaterialsName').length > 0 ? masterShowConfig.filter(item => item.sName === 'sMaterialsName')[0] : [];
      const printModePoConfig = masterShowConfig.filter(item => item.sName === 'iPrintModePo').length > 0 ? masterShowConfig.filter(item => item.sName === 'iPrintModePo')[0] : [];
      const positiveColorConfig = masterShowConfig.filter(item => item.sName === 'iPositiveColor').length > 0 ? masterShowConfig.filter(item => item.sName === 'iPositiveColor')[0] : [];
      const processNameConfig = masterShowConfig.filter(item => item.sName === 'sProcessName').length > 0 ? masterShowConfig.filter(item => item.sName === 'sProcessName')[0] : [];

      let configNew;
      allPartsName.forEach((item) => {
        configNew = { ...sumPQtyConfig };
        configNew.sName = `dSumPQty${item}`;
        masterShowConfig.push(configNew);

        configNew = { ...materialsNameConfig };
        configNew.sName = `sMaterialsName${item}`;
        masterShowConfig.push(configNew);

        configNew = { ...printModePoConfig };
        configNew.sName = `iPrintModePo${item}`;
        masterShowConfig.push(configNew);

        configNew = { ...positiveColorConfig };
        configNew.sName = `iPositiveColor${item}`;
        masterShowConfig.push(configNew);
        if (sBackProcessClassifyData !== '') {
          sBackProcessClassifyData.filter(processClassify => processClassify.sType !== '3').forEach((processClassify) => {
            configNew = { ...processNameConfig };
            configNew.sName = processClassify.sId + item;
            masterShowConfig.push(configNew);
          });
        }
      });
      if (sBackProcessClassifyData !== '') {
        sBackProcessClassifyData.filter(processClassify => processClassify.sType === '3').forEach((processClassify) => {
          configNew = { ...processNameConfig };
          configNew.sName = processClassify.sId;
          masterShowConfig.push(configNew);
        });
      }
    }
    const obj = commonFunc.mapPropsToFieldsChangeValue(masterShowConfig, workOrderData, Form);
    return obj;
  },
  onValuesChange(props, changedFields) {
    props.onChange(changedFields);
  },
})((props) => {
  const { app, form } = props;
  const {
    sActiveId,
    masterConfig,
    sId,
    formData,
    gdsjurisdiction,
    gdsformconst,
    dispatch,
    disabled,
    changeDataFlag,
    handleModalPane,
    handleSelectChange,
    content,
    workOrderData,
    workSlaveData,
    workOrderMaterialData,
    workOrderPrintData,
    workOrderJigSawData,
    hiddenProcess,
    listRecordKey,
    handleProductData,
    handleOutPrintData,
    handleMaterialData,
    handleJigSawData,
    handleRecordKey,
    handleDataCreate,
    handleGyChange,
    handleCalculate,
    handleAdd,
    handleEdit,
    handleDel,
    handleRefresh,
    handleSubmit,
    handleCancel,
    handleCopyTo,
    newIdlength,
    newIdFlag,
    handleWorkOrderPaneChange,
    onExamine,
    onCancelExamine,
    onPrintChild,
    onInvalid,
    onCancelInvalid,
    onNext,
    onPrior,
    onFirst,
    onLast,
    btnDataChild,
    selectStatus,
    gyCards,
    sBackProcessClassifyData,
  } = props;
  /* 主表 */
  const { /* tabBind, */ handleForm } = props;
  const childProps = {
    app, form, sActiveId, sId, disabled, dispatch, content, masterConfig, handleModalPane, handleSelectChange, gdsjurisdiction, gdsformconst,
  };
  const mainProps = {
    formData,
    componentName: 'workordermaster',
    gyCards,
    ...childProps,
    changeDataFlag,
    dataName: 'workOrderData',
    dataType: 'Map',
    dataSet: workOrderData,
    sBackProcessClassifyData,
    handleDataCreate,
    handleGyChange,
    handleCalculate, /* 计算 */
    newIdlength,
    newIdFlag,
  };
  const workOrderSlaveConfig = formData.filter(item => (item.sTbName.toLowerCase() === 'mftworkorderslave'))[0];
  const productProps = {
    formData,
    ...childProps,
    componentName: 'workorderslave',
    masterConfig: workOrderSlaveConfig !== undefined ? workOrderSlaveConfig : { sId: '' },
    changeDataFlag,
    dataName: 'workSlaveData',
    dataType: 'List',
    dataList: workSlaveData,
    dataExist: Object.keys(workSlaveData).length > 0,
    refreshList: listRecordKey.workSlaveDataKey === '',
    handleProductData,
    handleRecordKey,
    onExamine,
    onCancelExamine,
    onInvalid,
    onCancelInvalid,
    onNext,
    onPrior,
    onFirst,
    onLast,
    onPrintChild,
  };

  const workOrderMaterialConfig = formData.filter(item => (item.sTbName.toLowerCase() === 'mftworkordermaterials'))[0];
  const materialProps = {
    clickCloumn: { sName: 'sPartsName', keyName: 'sControlId' },
    handleWorkOrderPaneChange, /* 详情面板改变显示状态 */
    formData,
    ...childProps,
    componentName: 'workordermaterial',
    masterConfig: workOrderMaterialConfig !== undefined ? workOrderMaterialConfig : { sId: '' },
    changeDataFlag,
    dataName: 'workOrderMaterialData',
    dataType: 'List',
    dataList: workOrderMaterialData,
    refreshList: listRecordKey.workOrderMaterialDataKey === '',
    handleRecordKey,
    dataExist: Object.keys(workOrderMaterialData).length > 0,
    handleMaterialData,
    onExamine,
    onCancelExamine,
    onInvalid,
    onCancelInvalid,
    onNext,
    onPrior,
    onFirst,
    onLast,
    onPrintChild,
  };

  const workOrderPrintConfig = formData.filter(item => (item.sTbName.toLowerCase() === 'mftworkorderprocess'))[0];
  /* 过滤不显示的数据 */
  let i = 0;
  while (i < workOrderPrintData.length) {
    if (hiddenProcess.length > 0) {
      const workOrderPrintDataMap = JSON.parse(JSON.stringify(workOrderPrintData[i]));
      const printMap = hiddenProcess.filter(item => ((workOrderPrintDataMap.key !== undefined && item.sId === workOrderPrintDataMap.key) || (workOrderPrintDataMap.sId !== undefined && item.sId === workOrderPrintDataMap.sId)))[0];
      if ((workOrderPrintDataMap.key !== undefined && printMap !== undefined && workOrderPrintDataMap.key === printMap.sId) || (workOrderPrintDataMap.sId !== undefined && printMap !== undefined && workOrderPrintDataMap.sId === printMap.sId)) {
        workOrderPrintData.splice(i, 1);
        i -= 1;
      }
    }
    i += 1;
  }
  const printProps = {
    formData,
    ...childProps,
    componentName: 'workorderprint',
    masterConfig: workOrderPrintConfig !== undefined ? workOrderPrintConfig : { sId: '' },
    changeDataFlag,
    dataName: 'workOrderPrintData',
    dataType: 'List',
    dataList: workOrderPrintData,
    refreshList: listRecordKey.workOrderPrintDataKey === '',
    handleRecordKey,
    dataExist: Object.keys(workOrderPrintData).length > 0,
    handleOutPrintData,
    onExamine,
    onCancelExamine,
    onInvalid,
    onCancelInvalid,
    onNext,
    onPrior,
    onFirst,
    onLast,
    onPrintChild,
  };

  const workOrderJigSawConfig = formData.filter(item => (item.sTbName.toLowerCase() === 'mftworkordercontrol'))[0];
  const jigSawProps = {
    clickCloumn: { sName: 'sPartsNamePicArr' },
    handleWorkOrderPaneChange, /* 详情面板改变显示状态 */
    formData,
    ...childProps,
    componentName: 'workorderjigsaw',
    masterConfig: workOrderJigSawConfig !== undefined ? workOrderJigSawConfig : { sId: '' },
    changeDataFlag,
    dataName: 'workOrderJigSawData',
    dataType: 'List',
    dataList: workOrderJigSawData,
    refreshList: listRecordKey.workOrderJigSawDataKey === '',
    handleRecordKey,
    dataExist: Object.keys(workOrderJigSawData).length > 0,
    handleJigSawData,
    onExamine,
    onCancelExamine,
    onInvalid,
    onCancelInvalid,
    onNext,
    onPrior,
    onFirst,
    onLast,
    onPrintChild,
  };
  const bindProps = {
    formData,
    workOrderPrintData,
    workOrderJigSawData,
    hiddenProcess,
    onExamine,
    onCancelExamine,
    onInvalid,
    onCancelInvalid,
    onNext,
    onPrior,
    onFirst,
    onLast,
    onPrintChild,
  };
  /* 页签 */
  /* 主体内容表配置 refreshList用于弹窗数据回填后需要放行刷新动作 dataList列表数据下放 */
  const { bInvalid, bCheck } = workOrderData;
  const bShow = bInvalid || bCheck;
  let imgOption = '';
  if (bInvalid) {
    imgOption = <Avatar src={imgInvalid} />;
  } else if (bCheck) {
    imgOption = <Avatar src={imgCheck} />;
  }
  return (
    <Form>
      <Layout>
        <Header className={styles.header}>
          <Toolbar
            componentName="toolsalesorder"
            {...props}
            onAdd={handleAdd}
            onEdit={handleEdit}
            onBtnDel={handleDel}
            onBtnCancel={handleCancel}
            onRefresh={handleRefresh}
            onSubmit={handleSubmit}
            onCopyTo={handleCopyTo}
            onBtnExamine={onExamine}
            onBtnCancelExamine={onCancelExamine}
            onBtnInvalid={onInvalid}
            onBtnCancelInvalid={onCancelInvalid}
            onNext={onNext}
            onBtnPrior={onPrior}
            onBtnFirst={onFirst}
            onBtnLast={onLast}
            btnDataChild={btnDataChild}
            onBtnPrintChild={onPrintChild}
            bCheck={bCheck}
            selectStatus={selectStatus}
          >
            {handleForm(form)}
          </Toolbar>
        </Header>
        <Layout className={styles.clayout} id="workerOrder">
          <Content className={styles.content}>
            <div className={bShow ? styles.bShow : ''}>
              <div style={{ display: bShow ? 'block' : 'none' }}>
                {imgOption}
              </div>
            </div>
            <TabMainTable {...mainProps} />
            <TabProductTable {...productProps} />
            <TabJigSawTable {...jigSawProps} />
            <TabMaterialTable {...materialProps} />
            <TabPrintTable {...printProps} />
            <TabBindTable {...bindProps} />
          </Content>
        </Layout>
      </Layout>
    </Form>
  );
});


export default baseHigher(WorkOrder);
